package com.androidvizlab.bachelor.utilities;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * A utility class used to determine if there is an available
 * network connection and if background data usage is enabled
 * by the user.
 * 
 * @author The Hive
 */
public class ConnectivityDetector{

	private ConnectivityManager conManager = null; //Monitors network connectivity
	private NetworkInfo netInfoMOBILE = null; //Mobile
	private NetworkInfo netInfoWIFI = null; //WIFI
	private boolean isOnline = false; //Connection is available and device is connected1
	private boolean isAllowed = false; //Background Data usage
	private Context context = null; //Application context
	
	public ConnectivityDetector(Context context)
	{
		this.context = context;
		
		conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	}
	
	/**
	 * Determines if the device has an available network and if it is connected
	 * @return true if there is an available network and the device is connected.
	 */
	public boolean isConnectedToNetworkOnline()
	{	
		try
		{		
			if(conManager != null)
			{
				netInfoWIFI = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				netInfoMOBILE = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				
				if(netInfoWIFI != null && netInfoWIFI.isAvailable() && netInfoWIFI.isConnected())
				{
					isOnline = true;
				}
				else if(netInfoMOBILE != null && netInfoMOBILE.isAvailable() && netInfoMOBILE.isConnected())
				{
					isOnline = true;
				}
				else
				{
					isOnline = false;
				}		
			}
			
		}
		catch(Exception e)
		{
			Log.e("ConnectivityDetector class", e.toString());
			isOnline = false;
		}
		return isOnline;
	}
	
	/**
	 * Determines if the user allow the use of data usage for applications
	 * @return true if the background data usage is enabled.
	 */
	public boolean isBackgroundDataUsageAllowed()
	{	
		if(conManager != null)
		{
			isAllowed = conManager.getBackgroundDataSetting();
		}
		return isAllowed;
	}

	//*** GETTERS AND SETTERS
	
	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}
}
